package com.ks.composestudy.ui

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.ks.composestudy.MainViewModel
import com.ks.composestudy.ui.data.Chat

@Composable
fun ChatList(chats: List<Chat>) {
    Box(Modifier.background(Color.LightGray).fillMaxSize()) {
        LazyColumn(Modifier.background(Color.White).padding(5.dp)) {
            itemsIndexed(chats) { index, chat ->
                ChatItem(chat)
                if (index < chats.lastIndex) {
                    Divider(
                        Modifier.padding(45.dp, 0.dp, 0.dp, 0.dp),
                        0.8f.dp,
                        color = Color.LightGray
                    )
                }
            }
        }
    }
}

@Composable
fun ChatItem(chat: Chat) {
    val viewModel: MainViewModel = viewModel()
    Row(Modifier.clickable {
        viewModel.startChat(chat = chat)
    }) {
        Image(
            painterResource(chat.friend.avatar),
            chat.friend.name,
            Modifier.padding(5.dp).unread(!chat.msgs.last().read)
                .align(Alignment.CenterVertically)
        )
        Column(Modifier.weight(1f).padding(5.dp)) {
            Text(
                chat.friend.name,
                Modifier.padding(vertical = 5.dp),
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
                color = Color.Black,
            )
            Text(
                chat.msgs.last().text, fontSize = 11.sp,
                fontWeight = FontWeight.Normal,
                color = Color.Gray
            )
        }
        Text(
            chat.msgs.last().time,
            Modifier.align(Alignment.CenterVertically),
            color = Color.Gray,
            fontSize = 11.sp,
            fontWeight = FontWeight.SemiBold
        )
    }
}

@Preview(showBackground = true)
@Composable
fun ChatListPreview() {
    val viewModel: MainViewModel = viewModel()
    ChatList(viewModel.chats)
}